package cn.wolfcode.mqListener;

import cn.wolfcode.MQ.MQConstant;
import cn.wolfcode.MQ.OrderMQResult;
import cn.wolfcode.core.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

/**
 * @author zhangh
 * @version 1.0
 * @date 2025/9/26 10:05
 * @description: 步骤三[通知客户] websocket监听[创建订单]消息，可能存在
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstant.SECKILL_ORDER_RESULT_TOPIC,
        consumerGroup = MQConstant.SECKILL_ORDER_RESULT_GROUP
)
public class WebSocketOrderMessageListener implements RocketMQListener<OrderMQResult> {

    @Override
    public void onMessage(OrderMQResult orderMQResult) {

        String mqResultJson = JSON.toJSONString(orderMQResult);
        log.info("步骤三[通知客户]，收到订单结果：{}", mqResultJson);


        try {
            int count = 0;

            //自旋重试
            while (count++ < 5) {
                // 根据token获取session对象
                Session session = WebSocketServer.SESSION_MAP.get(orderMQResult.getToken());
                if (session != null) {
                    // 通过session对象获得远程连接 发送信息给前端
                    session.getBasicRemote().sendText(mqResultJson);
                    return;
                }
                log.info("步骤三[通知客户] 第{}次查询session信息失败", count);
                Thread.sleep(200);
            }


        } catch (Exception e) {
            log.info(e.getMessage());
        }


    }
}
